﻿using System.Buffers;
using SuperSocket.ProtoBase;
using Xph.Sag.Kernel;

namespace Example.Modbus.Kernel;

/// <summary>
/// XPH数据校验过滤器
/// </summary>
public class Crc16Filter : PipelineFilterBase<XphPackage>
{
    public override XphPackage Filter(ref SequenceReader<byte> reader)
    {
        var pack = reader.Sequence.Slice(0, reader.Length);
        var data = pack.Slice(0, reader.Length - 2);
        var tar = pack.Slice(reader.Length - 2, 2);
        var cal = data.ToArray().CRC16();              
        if (!cal.Check(tar.ToArray()))
        {
            reader.Advance(reader.Length);
            return new XphPackage();
        }
        reader.Advance(reader.Length);
        return DecodePackage(ref pack);
    }
}